package com.example.rule.core;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jason - Chusifeng
 * @version 1.0.0
 * @ClassName Facts.java
 * @PackageName com\welab\vb\payment\transaction\rule\core\Facts.java
 * @Description 加载所有事实
 * @createTime 2022年10月10日 10:48:42
 */
public class Facts {

    private List<Fact> facts;

    public Facts(List<Fact> facts) {
        this.facts = facts;
    }
    public Facts() {
        facts = new ArrayList<>();
    }

    public void addFact(Fact fact){
        Fact retrievedFact = getFact(fact.getMark());
        if (null != retrievedFact) {
            remove(retrievedFact);
        }
        facts.add(fact);
    }

    private void remove(Fact fact) {
        if (null == fact)  {
            return;
        }
        facts.remove(fact);
    }

    public Fact getFact(String factMark) {
       return facts.stream()
                .filter(fact -> fact.getMark().equals(factMark))
                .findFirst()
                .orElse(null);
    }

    public List<Fact> getFacts(){
        return this.facts;
    }

    public Map<String, Object> asMap() throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        for (Fact fact : facts) {
            Class cls  = fact.getClass();
            while (cls!=null) {
                Field[] fields = cls.getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    map.put(field.getName(),field.get(fact));
                }
                cls = cls.getSuperclass();
            }
        }
        return map;
    }
}
